package com.wiz.weixin.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wiz.weixin.common.Constant;
import com.wiz.weixin.common.GlobalConstant;
import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.mapper.AgentMapper;
import com.wiz.weixin.mapper.TencentMapper;
import com.wiz.weixin.service.MemberService;
import com.wiz.weixin.tencent.VO.Article;
import com.wiz.weixin.util.CacheMap;
import com.wiz.weixin.util.JSSDKUtil;
import com.wiz.weixin.util.MiscUtil;
import com.wiz.weixin.util.WxMessageUtil;


/**
 * 腾讯相关逻辑器
 * @author Hakeny
 */
@Service("tencentManager")
public class TencentManager implements TencentConstant{
	private transient final Logger log = LoggerFactory.getLogger(getClass());

	private final String reset_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WX_APP_ID+"&secret="+WX_APP_SECRET;
	private final String web_token_url="https://api.weixin.qq.com/sns/oauth2/access_token";
	
	@Resource
	public TencentMapper tencentMapper;
	@Resource
	public AgentMapper agentMapper;
	@Resource
	public AgentManager agentManager;
	@Resource
	private HttpManager httpManager;
	@Resource
	private MenuManager menuManager;
	@Resource
	private MemberService memberService;
	
	/**
	 * 重置token
	 * @return
	 * @throws JSONException
	 */
	public boolean resetWxToken() throws JSONException{
		log.info("reseting token ~~~~~~~~~~~~~~");
		String response = httpManager.getHttpsResponseByGet(reset_token_url);
    	JSONObject json = new JSONObject(response);
		String token = json.getString("access_token");//expires_in时间参数暂时忽略
		log.info("token===========>"+token);
		if(StringUtils.isNotBlank(token)){
			GlobalConstant.tencent_wx_token = token;
			return true;
		}
    	return false;
	}
	
	/**
	 * 通过微信要求获取用户网页授权的方式获取用户的openId
	 * @return
	 * @throws JSONException 
	 */
	public String getOpenId(String code) throws JSONException{
		Map<String,String> params = new HashMap<String,String>();
		params.put("appid", WX_APP_ID);
		params.put("secret", WX_APP_SECRET);
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		// 调用接口创建菜单
		String response = httpManager.getHttpsResponseByPost(web_token_url, params, "utf-8");
		System.out.println("openid===========>"+response);
		JSONObject json = new JSONObject(response);
		
		if(!json.isNull("openid")){
			return json.getString("openid");
//			return "ovNRGs8IVk3ctBk5YLcxE45XG50";
		}
		return null;
	}
	
	/**
	 * 根绝配置文件建立微信menu
	 * @throws JSONException 
	 */
	public String createMenu() throws JSONException{
		if(menuManager.getMenu() !=0 ){
			return "fail";
		}
		return "success";
	}
	
	/**
	 * 绑定微信
	 * @param account
	 * @param password
	 * @param openid
	 * @return
	 */
	public String bindLogin(String account,String password,String openid){
		int agentAdminId = agentMapper.getAgentAdminId(account, MiscUtil.encodeByMd5(password));
		if(agentAdminId==0){
			return "账号信息错误";
		}
		int count = tencentMapper.countTencentWxRelationByAgentId(agentAdminId);
		if(count != 0){
			return "您已经绑定过微信号";
		}
		int result = tencentMapper.createTencentWxRelation(agentAdminId, openid);
		if(result<1){
			return "绑定失败，请联系管理员";
		}
		return "绑定成功";
	}
	
	
	/**
	 * 处理微信发来的请求
	 *
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";
			// xml 请求解析
			Map<String, String> requestMap = WxMessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型，需要根据此消息判断是何种消息
			String msgType = requestMap.get("MsgType");
			log.info("recive msg from "+fromUserName+"   and msgtype="+msgType);
			if(msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_TEXT)){// 只响应文本消息
				String content = requestMap.get("Content");
				if (content.startsWith("BD")) {
					String phoneNum = content.substring(2);
					if (phoneNum.length() != 11) {
						respContent = "手机长度不合法";
					} else {
						respContent = agentManager.bindAgentMemberByPhone(fromUserName, phoneNum);
					}
					// 回复文本消息
//					WxSendTextMessage textMessage = new WxSendTextMessage();
//					textMessage.setToUserName(fromUserName);
//					textMessage.setFromUserName(toUserName);
//					textMessage.setCreateTime(new Date().getTime());
//					textMessage.setMsgType(WxMessageUtil.RESP_MESSAGE_TYPE_TEXT);
//					textMessage.setFuncFlag(0);
//					textMessage.setContent(respContent);
//					respMessage = WxMessageUtil.textMessageToXml(textMessage);
				}
			}else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				 // 事件类型
				 String eventType = requestMap.get("Event");
				 String eventKey = requestMap.get("EventKey");
				 log.info("eventType===========>"+eventType);
				 log.info("eventKey===========>"+eventKey);
				 // 订阅
				 if (eventType.equals(WxMessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					 if(eventKey != null && !eventKey.equals("")){
						 StringBuffer buffer = new StringBuffer();
						 buffer.append("欢迎关注").append("\n\n\n");
						 buffer.append("[");
						 buffer.append(eventKey);
						buffer.append("]").append("\n\n\n");
						
						buffer.append("<a href=\"http://wx.wiz-tech.com.cn/client/listResidualAmount?param="+eventKey+"\">点击这里，注册</a>").append("\n");
						respContent = buffer.toString();
					 }
					 else{
						 respContent = "欢迎关注油掌柜！！！";
					 }
					 respMessage = WxMessageUtil.textMessageToXml(fromUserName,toUserName,respContent);
				 }//扫描
				 else if(eventType.equals(WxMessageUtil.EVENT_TYPE_SCAN)){
//					 Constant.map.put("", fromUserName);
					 int vcode=(int)(Math.random()*999999);
					 Constant.map.put(String.valueOf(vcode), fromUserName);
					 
					 StringBuffer buffer = new StringBuffer();
					 buffer.append("[");
					 buffer.append(eventKey);
					buffer.append("]").append("\n\n\n");
						// 回复文本消息
					String url = Constant.MEMBER_REGISTER_URL.replace("PARAM", eventKey)
							.replace("RAND", String.valueOf(vcode));
							
					buffer.append("<a href=\""+url+"\">点击这里，注册</a>").append("\n");	
					respContent = buffer.toString();
					respMessage = WxMessageUtil.textMessageToXml(fromUserName,toUserName,respContent);
				 }else if(eventType.equals(WxMessageUtil.EVENT_TYPE_CLICK)){
					// 事件 KEY 值，与创建自定义菜单时指定的 KEY 值对应
					 if (eventKey.equals("WX_SCAN_REFUELING")) {
						respContent = "扫一扫加油被点击！";
						
						// 创建图文消息
						
						List<Article> articleList = new ArrayList<Article>();
						Article article = new Article();
						article.setTitle("我的账户");
						// 图文消息中可以使用 QQ 表情、符号表情
						article.setDescription("孵化园加油站\n账户余额：500元\n\n孵化园加油站\n账户余额：700元\n\n\n点击这里，查询收支明细");
						// 将图片置为空
						article.setPicUrl("");
						article.setUrl("http://www.baidu.com");
						articleList.add(article);
						respMessage = WxMessageUtil.newsMessageToXml(fromUserName,toUserName,articleList);
						
					}else if(eventKey.equals("WX_MY_BALANCE")){
						StringBuffer buffer = new StringBuffer();
						String amounts = memberService.amounts(fromUserName);
						buffer.append(amounts);
						buffer.append("<a href=\""+Constant.AMOUNT_DETAIL_URL+"\">点击这里，查询收支明细</a>").append("\n");
						respContent = buffer.toString();
						// 回复文本消息
						respMessage = WxMessageUtil.textMessageToXml(fromUserName,toUserName,respContent);
					}
					 //扫扫
					else if(eventKey.equals("SCAN_MEUN1")){
						System.out.println("=====================>>扫扫");
					}
				 }else if(eventType.equals("LOCATION")){
					 
					double Latitude = Double.valueOf(requestMap.get("Latitude"));
					double Longitude =  Double.valueOf(requestMap.get("Longitude"));
					System.out.println("=============================>>LOCATION");
					System.out.println(Latitude+"============="+Longitude);
					System.out.println("=============================>>LOCATION");
					 
				 }
				 
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}
	/**
     * 长链接转成短链接 提高扫码速度和成功率
     *
     * @param accessToken
     * @param URL
     * @return
     */
    public static String shortURL(String URL)throws Exception {
        String shortURL = null;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", GlobalConstant.tencent_wx_token);
        String jsonMsg = "{\"action\":\"long2short\",\"long_url\":\"%s\"}";
        System.out.println(String.format(jsonMsg, URL));
        String response = JSSDKUtil.httpsRequest(requestUrl, "POST", String.format(jsonMsg, URL));
        org.json.JSONObject jsonObject = new org.json.JSONObject(response);
        String code = jsonObject.getString("errcode");
        if(code.equals("0")){
        	shortURL = jsonObject.getString("short_url");
        }else{
        	String errorMsg = jsonObject.getString("errmsg");
        	throw new Exception(errorMsg);
        }
        return shortURL;
    }
	private void getDefault() {
		// TODO Auto-generated method stub
		
	}
}
